/**
 * @file createStringField
 * @author fanxueliang@qq.com
 */
import {isEmpty, map} from 'lodash-es';
import type {StringSpecItem, EnumValuesSpecItem, StringLikeField, FieldDatasource, ExtensionsAttr} from '../interface';
import {getBasicField} from '../util';

export function createStringField(spec: StringSpecItem, showIndex: number, path: string) {
    let component = 'Input';
    if (spec?.multiline) {
        component = 'Textarea';
    }
    if (spec?.ui) {
        component = spec.ui;
    }
    const datasource = map<EnumValuesSpecItem, FieldDatasource>(spec.enumValues, (enumItem) => ({
        label: enumItem.displayName,
        value: enumItem.value
    }));

    const basicField = getBasicField(spec, path, showIndex);
    const {api = null, payload = null, useSource = null} = spec.extraAttr ? spec.extraAttr.remote || {} : {};
    const extensions: ExtensionsAttr[] = [];
    if (spec?.extraAttr?.extensions) {
        extensions.push(...spec.extraAttr.extensions);
    }
    if (api || !isEmpty(useSource)) {
        extensions.push({
            name: 'manualVerification'
        });
    }
    return {
        ...basicField,
        extensions,
        type: 'STRING',
        isLeaf: true,
        spec,
        component,
        datasource,
        api,
        payload,
        useSource
    } as StringLikeField;
}
